package com.harrison.service;

import com.harrison.client.AuthServiceClient;
import com.harrison.dao.UserDao;
import com.harrison.dto.LoginDTO;
import com.harrison.dto.RespDTO;
import com.harrison.entity.JWT;
import com.harrison.entity.User;
import com.harrison.exception.CommonException;
import com.harrison.exception.ErrorCode;
import com.harrison.util.BPwdEncodingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Auther: harrison
 * @Date: 2019/6/24 09:44
 * @Description:
 */
@Service
public class UserService {

    @Autowired
    UserDao userDao;
    @Autowired
    AuthServiceClient authServiceClient;

    public User createUser(User user){
        return userDao.save(user);
    }

    public User getUserInfo(String username){
        return userDao.findByUsername(username);
    }

    public RespDTO login(String username,String password){
        User user = userDao.findByUsername(username);
        if (null==user){
            throw new CommonException(ErrorCode.USER_NOT_FOUND);
        }

        if (!BPwdEncodingUtils.matches(password,user.getPassword())){
            throw new CommonException(ErrorCode.USER_PASSWORD_ERROR);
        }

        JWT jwt = authServiceClient.getToken("Basic dWFhLXNlcnZpY2U6MTIzNDU2", "password", username, password);

            // 获得用户菜单
            if (null==jwt){
                throw new CommonException(ErrorCode.GET_TOKEN_FAIL);
            }
            LoginDTO loginDTO = new LoginDTO();
            loginDTO.setToken(jwt.getAccess_token());
            loginDTO.setUser(user);
            return RespDTO.onSuc(loginDTO);

    }
}
